package com.temple.common.utils;

import org.apache.commons.codec.binary.Base64;
import org.apache.commons.codec.digest.DigestUtils;

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;


public class Sha256EncryptionUtil {
    /**
     * getBodyDigest
     * @param body
     * @return
     * @throws Exception
     */
    public static String getBodyDigest(String body) throws Exception {
        byte[] data = body.getBytes("UTF-8");

        InputStream is = new ByteArrayInputStream(data);

        try {
            return DigestUtils.sha256Hex(is);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }


    public static String encryption(String data, String key) throws Exception {
        String algorithm = "HmacSHA256";
        Mac mac = Mac.getInstance(algorithm);
        mac.init(new SecretKeySpec(key.getBytes(), algorithm));

        byte[] encryData = mac.doFinal(data.getBytes());

        return Base64.encodeBase64String(encryData);
    }


    public static void main(String [] args){
        String key = "fcAmtnx7MwismjWNhNKdHC44mNXtnEQeJkRrhKJwyrW2ysRR";

        String data ="{\"walletOption\":\"SINGLE\",\"totalAmount\":\"1\",\"msgType\":\"bills.getQRCode\",\"requestTimestamp\":\"2017-06-26 17:28:02\",\"msgSrc\":\"WWW.TEST.COM\",\"sign\":\"2631915B7F7822C4B00A488A32E03764\",\"goods\":[{\"quantity\":\"1\",\"price\":\"1\",\"goodsId\":\"1\",\"goodsCategory\":\"TEST\",\"body\":\"微信二维码测试\",\"goodsName\":\"微信二维码测试\"}],\"mid\":\"898340149000005\",\"billDate\":\"2017-06-26\",\"billNo\":\"31940000201700002\",\"tid\":\"88880001\",\"instMid\":\"YUEDANDEFAULT\"}";

//        Map<String,String> mapType = JSON.parseObject(data,Map.class);
//        for(Map.Entry<String,String> entry:mapType.entrySet()){
//            System.out.println(entry.getKey());
//            System.out.println(entry.getValue());
//        }

//        JSONObject jsonObject = JSON.parseObject(data);
//        System.out.println(jsonObject.toJSONString());
//
//        Map<String,String> map = YsUtil.jsonToMap(jsonObject);
//
//        String  encryptionData = YsUtil.buildSignString(mapType);

        try {
            System.out.println(encryption(data,key));
//            a9eced8dd8425d1fc4047cf94e672c69ed1073557ee831c51287341cfab0b21f
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


}
